<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <v-distpicker only-province @selected="onSelected" v-if="preRoleType === '1'">
        </v-distpicker>
        <el-select v-model="badStockDto.cityCode" placeholder="请选择地市"
                   v-if="(badStockDto.roleType === 2 && preOfficeType === '0') || (badStockDto.roleType === 3 &&
                   preOutsourceType === '1')" @change="onCityChange()">
          <el-option
            v-for="item in addressOption"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <!--网点类型查询-->
      <el-form-item v-if="badStockDto.roleType === 1 || preOfficeType === '0'">
        <el-select v-model="badStockDto.pointType" placeholder="请选择网点类型" @change="onPointChange()">
          <el-option
            v-for="item1 in pointTypeOptions"
            :key="item1.id"
            :label="item1.name"
            :value="item1.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="badStockDto.pointType === 0 && preOfficeType !== '1'">
        <el-select v-model="badStockDto.pointId" placeholder="请选择办事处" clearable>
          <el-option
            v-for="item1 in pointOptions"
            :key="item1.id"
            :label="item1.name"
            :value="item1.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="badStockDto.pointType === 1 && preOutsourceType !== '0'">
        <el-select v-model="badStockDto.pointId" placeholder="请选择外包商" clearable>
          <el-option
            v-for="item1 in outsourceOptions"
            :key="item1.id"
            :label="item1.company"
            :value="item1.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
      <el-select v-model="badStockDto.status" placeholder="请选择库存状态">
        <el-option
          v-for="item1 in statusList"
          :key="item1.id"
          :label="item1.name"
          :value="item1.id">
        </el-option>
      </el-select>
    </el-form-item>
      <el-form-item>
        <el-input placeholder="YSTSN" v-model="badStockDto.ystsn" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchDate()">查询</el-button>
      </el-form-item>
      <el-form-item v-if="preRoleType === '2' || preRoleType === '3'">
        <el-dropdown @command="handleCommand">
          <el-button type="primary">导入<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <a href="/static/不良品库导入模板.xlsx" download="不良品库导入模板.xlsx" style="color:#5a5e66;text-decoration: none "><el-dropdown-item command="handleDownload">模板下载</el-dropdown-item></a>
            <el-dropdown-item command="handleImport">数据导入</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-form-item>
    </el-form>
    <custom-table
      :data="badStockList"
      :columns="columns"
      :tableLoadingFlag="tableLoadingFlag"
      :operationColumn="operationColumn"
      :pagination="pagination">
    </custom-table>

    <el-dialog title="维修记录" :visible.sync="detailDialogVisible" :close-on-click-modal="false">
      <repair-list
        :ystsn="ystsn">
      </repair-list>
      <div slot="footer">
        <el-button type="primary" @click="onBtnCancel()">取消</el-button>
      </div>
    </el-dialog>

    <!-- 不良品模板导入模态框 -->
    <el-dialog title="模板导入" :visible.sync="uploadVisible"
               :close-on-click-modal="false" :before-close="uploadCancel">
      <div>
        <el-form label-width="80px" ref="uploadForm" :inline="true">
          <el-form-item style="padding-left: 120px">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="myHeaders"
              name="file"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeAvatarUpload"
              multiple
              drag
              :limit="1"
              :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/>只能上传xlsx文件，且不超过10M</div>
            </el-upload>
          </el-form-item>
          <!--显示导入中错误的数据-->
          <div style="height: 200px;overflow-y: auto" v-if="hideTable">
            <custom-table
              :data="wrongDataList"
              :columns="wrongDetailColumns">
            </custom-table>
          </div>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="uploadCancel()">确定</el-button>
      </div>
    </el-dialog>

    <!--编辑功能模态框-->
    <el-dialog title="编辑" :visible.sync="editVisible" :close-on-click-modal="false">
      <div text-align="center">
        <el-form :model="editDto"  label-width="120px" ref="editForm">
          <el-form-item label="型号"prop="model">
            <el-select style="width:180px;" v-model="editDto.modelId" clearable placeholder="请选择型号">
              <el-option
                v-for="item in allModel"
                :key="item.id"
                :label="item.code"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工厂"prop="factoryName">
            <el-select v-model="editDto.factoryId" placeholder="请选择工厂">
              <el-option
                v-for="item1 in factoryOptions"
                :key="item1.id"
                :label="item1.name"
                :value="item1.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="YSTSN"prop="ystsn">
            <el-input v-model="editDto.ystsn"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="editCancel()">取消</el-button>
        <el-button type="primary" @click="editConfirm()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import { apiGetBadStockList, apiGetRepairHistory, apiGetReturnFactory, apiUpdateBadStockDevice } from '@/api/stock/index'
  import { apiGetCityListByProvinceCode, apiGetModelList, apiGetAllPointOffice } from '@/api/dictionary'
  import { getRoleType, getOfficeType, getCityCode, getProvinceCode, getOutsourceType } from '@/utils/token'
  import { parseTime } from '@/utils'
  import {baseInfo} from '@/utils/fetch'
  import store from '@/store'
  import { apiBadStockReadExcel } from '@/api/excel/excelRead'
  import RepairList from '../../../components/table/RepairList.vue'
  import {apiGetOutsourcerList} from '@/api/basic/info/outsourcer'
  import {apiGetOfficeList} from '@/api/basic/info/inside/office'

  export default {
    components: {
      RepairList,
      CustomTable},
    created() {
      this.preOfficeType = getOfficeType()
      this.preOutsourceType = getOutsourceType()
      this.preRoleType = getRoleType()
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      if (getRoleType() === '2') {
        this.badStockDto.roleType = 2
        listQuery.province = getProvinceCode()
        this.badStockDto.provinceCode = getProvinceCode()
        if (getOfficeType() === '1') {
          listQuery.city = getCityCode()
          this.badStockDto.cityCode = getCityCode()
        }
        this.selectedAddressInit()
      }
      if (getRoleType() === '3') {
        this.badStockDto.roleType = 3
        listQuery.province = getProvinceCode()
        this.badStockDto.provinceCode = getProvinceCode()
        this.badStockDto.pointType = 1
        if (getOutsourceType() === '0') {
          listQuery.city = getCityCode()
          this.badStockDto.cityCode = getCityCode()
        }
        this.selectedAddressInit()
      }
      this.getBadStockList(listQuery)
      this.getAllModel()
      this.selectFactoryList()
      this.getOffice()
      this.getOutsource()
    },
    data() {
      return {
        pointOptions: [],
        outsourceOptions: [],
        uploadUrl: baseInfo() + '/api/v1/upload',
        myHeaders: {'access_token': store.getters.token},
        // 上传文件显示
        fileList: [],
        // 文件上传路径
        importFileUrl: baseInfo() + '/api/v1/upload',
        // 文件上传参数
        upLoadData: {},
        filePath: '',
        uploadVisible: false,
        hideTable: false,
        wrongDetailColumns: [
          {label: '错误行号', name: 'wrongRowNO', width: '77', height: '40', align: 'center'},
          {label: '错误原因', name: 'reason', width: '120', height: '40', align: 'center'},
          {label: '品牌', name: 'brand', align: 'center'},
          {label: '型号', name: 'model', align: 'center'},
          {label: 'YSTSN', name: 'ystsn', align: 'center'},
          {label: '返厂工厂', name: 'returnFactory', align: 'center'},
          {label: '故障现象', name: 'faultAppearance', align: 'center'}
        ],
        tableLoadingFlag: false,
        // 不良品库存一览表
        columns: [
          {label: '品牌', name: 'brand', align: 'center'},
          {label: '型号', name: 'model', width: '100', align: 'center'},
          {label: '省份', name: 'provinceName', align: 'center'},
          {label: '城市', name: 'cityName', align: 'center'},
          {label: 'YSTSN', name: 'ystsn', width: '220', align: 'center'},
          {label: '是否客户机', name: 'isReturn', width: '120', align: 'center'},
          {label: '入库时间', name: 'inStockTime', width: '160', align: 'center', formatter: this.formatTime},
          {label: '保修截止日期', name: 'deadLine', width: '160', align: 'center', formatter: this.formatTime},
          {label: '库存状态', name: 'statusStr', width: '120', align: 'center'}
        ],
        badStockList: [],
        addressOption: [],
        editVisible: false,
        // 型号
        allModel: [],
        // 工厂
        factoryOptions: [],
        preOfficeType: null,
        badStockDto: {
          provinceCode: '',
          cityCode: '',
          pointType: 0,
          roleType: 1,
          status: 0,
          ystsn: '',
          pointRange: 0
        },
        // 编辑DTO
        editDto: {
          ystsn: '',
          modelId: '',
          id: '',
          factoryId: '',
          status: '',
          isReturn: ''
        },
        operationColumn: {
          width: '100',
          operations: [
            {name: '维修病例', callback: this.onBtnRepairHistory},
            {name: '编辑', callback: this.handleEdit, page: 'badStockEdit'}
          ]
        },
        detailTableLoadingFlag: false,
        detailDialogVisible: false,
        pagination: this.getData(this.getBadStockList),
        pointTypeOptions: [
          {
            'id': 0,
            'name': '办事处'
          },
          {
            'id': 1,
            'name': '外包商'
          }
        ],
        preRoleType: getRoleType(),
        ystsn: '',
        statusList: [
          {id: 0, name: '在库'},
          {id: 1, name: '出库到良品库'},
          {id: 2, name: '在途返厂维修'},
          {id: 3, name: '工厂已收机'},
          {id: 4, name: '返还客户'},
          {id: 5, name: '待返厂'},
          {id: 6, name: '出库到报废库'},
          {id: 7, name: '特殊出库'}
        ]
      }
    },
    methods: {
      uploadCancel () {
        this.uploadVisible = false
        this.wrongDataList = []
        this.fileList = []
        this.hideTable = false
        this.$refs['uploadForm'].resetFields()
      },
      handleCommand(command) {
        if (command === 'handleImport') {
          this.dialogType = 'upload'
          this.uploadVisible = true
        } else if (command === 'handleDownload') {
        }
      },
      uploadSuccess (response, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传文件成功!'
        })
        let filePath = response.data
        this.excelRead(filePath)
      },
      // 上传错误
      uploadError (err, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传失败，请重试！'
        })
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload (file) {
        const extension = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension) {
          this.$message({
            showClose: true,
            message: '上传模板只能是 xlsx 格式!'
          })
        }
        if (!isLt2M) {
          this.$message({
            showClose: true,
            message: '上传模板大小不能超过 10MB!'
          })
        }
        return extension && isLt2M
      },
      excelRead (filePath) {
        apiBadStockReadExcel({'filePath': filePath}).then(response => {
          if (response.data) {
            this.wrongDataList = response.data
            this.hideTable = true
          } else {
            this.$message({
              showClose: true,
              message: '导入执行中，请稍后',
              type: 'success'
            })
            this.hideTable = false
            this.getBadStockList({
              pageNumber: this.pagination.currentPage,
              pageSize: this.pagination.pageSize
            })
          }
          this.fileList = []
        })
      },
      // 地址初始化
      selectedAddressInit() {
        let listquery = {
          province: getProvinceCode()
        }
        apiGetCityListByProvinceCode(listquery).then(response => {
          let cityList = response.data
          let city = []
          let temp = {}
          for (let i in cityList) {
            if (!temp[cityList[i].name]) {
              temp[cityList[i].name] = cityList[i].code
            }
          }
          city.push({'name': '全部地市', 'code': ''})
          for (let k in temp) {
            city.push({'name': k, 'code': temp[k]})
          }
          this.addressOption = city
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      getBadStockList(listQuery) {
        if (undefined === listQuery.province) {
          if (this.badStockDto.provinceCode === '') {
            if (getRoleType() === '2') {
              listQuery.province = getProvinceCode()
              if (getOfficeType() === '1') {
                listQuery.city = getCityCode()
              }
            }
          } else {
            listQuery.province = this.badStockDto.provinceCode
          }
        }
        if (undefined === listQuery.status) {
          listQuery.status = this.badStockDto.status
        }
        if (undefined === listQuery.ystsn) {
          listQuery.ystsn = this.badStockDto.ystsn
        }
        if (!listQuery.pointType) {
          listQuery.pointType = this.badStockDto.pointType
        }
        if (!listQuery.pointId) {
          listQuery.pointId = this.badStockDto.pointId
        }
        // TODO 获取库存一览表
        this.tableLoadingFlag = true
        apiGetBadStockList(listQuery).then(response => {
          this.badStockList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      onSelected(data) {             // 省市区联动回调
        this.badStockDto.provinceCode = data.province.code
      },
      // 条件查询
      searchDate() {
        let listQuery = {
          pageNumber: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          province: this.badStockDto.provinceCode,
          city: this.badStockDto.cityCode,
          pointType: this.badStockDto.pointType,
          pointId: this.badStockDto.pointId,
          ystsn: this.badStockDto.ystsn
        }
        if (getRoleType() === '2' || getRoleType() === '3') {
          listQuery.province = getProvinceCode()
        }
        if (getOfficeType() === '1') {
          listQuery.city = getCityCode()
        }
        this.badStockList = []
        this.pagination.totalRecords = 0
        this.getBadStockList(listQuery)
      },
      // 弹出维修一览界面
      onBtnRepairHistory(row) {
        this.detailDialogVisible = true
        this.ystsn = row.ystsn
      },
      // 关闭弹出框
      onBtnCancel() {
        this.detailTableLoadingFlag = false
        this.tableLoadingFlag = false
        this.detailDialogVisible = false
      },
      // 编辑按钮
      handleEdit (row) {
        this.editVisible = true
        this.editDto.id = row.id
        this.editDto.ystsn = row.ystsn
        this.editDto.status = row.status
        this.editDto.isReturn = row.isReturn
        this.editDto.factoryId = row.returnFactoryId
        this.editDto.modelId = row.modelId
      },
      editCancel () {
        this.editVisible = false
        this.$refs['editForm'].resetFields()
        this.editDto = {
          ystsn: '',
          modelId: '',
          factoryId: ''
        }
      },
      // 确认编辑
      editConfirm () {
        apiUpdateBadStockDevice(this.editDto).then(() => {
          this.$message({
            showClose: true,
            message: '编辑成功',
            type: 'success'
          })
          this.editCancel()
          this.searchDate()
        })
      },
      getAllModel () {
        apiGetModelList().then(response => {
          this.allModel = response.data
        })
      },
      selectFactoryList () {
        apiGetReturnFactory().then(response => {
          let factoryList = response.data
          let factory = []
          let temp = {}
          for (let i in factoryList) {
            if (!temp[factoryList[i].name]) {
              temp[factoryList[i].name] = factoryList[i].id
            }
          }
          for (let k in temp) {
            factory.push({'name': k, 'id': temp[k]})
          }
          this.factoryOptions = factory
        }).catch(() => {
        })
      },
      onCityChange () {
        if (this.badStockDto.pointType === 0) {
          let listQuery = {
            province: this.badStockDto.provinceCode,
            city: this.badStockDto.cityCode
          }
          this.pointOptions = []
          this.getOfficeByCity(listQuery)
        } else {
          let listQuery = {
            provinceCode: this.badStockDto.provinceCode,
            cityCode: this.badStockDto.cityCode
          }
          this.outsourceOptions = []
          this.getOutsourceByCity(listQuery)
        }
      },
      onPointChange () {
        if (this.badStockDto.pointType === 0) {
          let listQuery = {
            province: this.badStockDto.provinceCode,
            city: this.badStockDto.cityCode
          }
          this.pointOptions = []
          this.getOfficeByCity(listQuery)
        } else {
          let listQuery = {
            provinceCode: this.badStockDto.provinceCode,
            cityCode: this.badStockDto.cityCode
          }
          this.outsourceOptions = []
          this.getOutsourceByCity(listQuery)
        }
      },
      // 获取网点一览
      getOffice () {
        let listQuery = {
          provinceCode: this.badStockDto.provinceCode,
          pageNumber: 1,
          pageSize: 100
        }
        apiGetOfficeList(listQuery).then(response => {
          this.pointOptions = response.data
        })
      },
      // 获取外包商一览
      getOutsource () {
        let listQuery = {
          provinceCode: this.badStockDto.provinceCode,
          pageNumber: 1,
          pageSize: 100
        }
        apiGetOutsourcerList(listQuery).then(response => {
          this.outsourceOptions = response.data
        })
      },
      // 按地区条件获取网点
      getOfficeByCity (listQuery) {
        this.badStockDto.pointId = ''
        apiGetAllPointOffice(listQuery).then(response => {
          this.pointOptions = response.data
        })
      },
      // 按地区获取外包商
      getOutsourceByCity (listQuery) {
        this.badStockDto.pointId = ''
        listQuery.pageNumber = 1
        listQuery.pageSize = 100
        apiGetOutsourcerList(listQuery).then(response => {
          this.outsourceOptions = response.data
        })
      },
      formatTime(row, column, cellValue) {
        if (column.property === 'deadLine') {
          return parseTime(cellValue, '{y}-{m}-{d}')
        } else {
          return parseTime(cellValue)
        }
      }
    }
  }
</script>
